package com.pms.controller;

import com.pms.pojo.DailyTask;
import com.pms.result.Result;
import com.pms.service.DailyTaskService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/sysUser")
public class DailyTaskController {

    @Autowired
    private DailyTaskService dailyTaskService;

    @GetMapping("/daily-tasks")
    public Result<List<DailyTask>> getCurrentUserTasks() {
        try {
            List<DailyTask> tasks = dailyTaskService.getCurrentUserTasks();
            return Result.success(tasks);
        } catch (Exception e) {
            log.error("获取任务列表失败", e);
            return Result.error("获取任务列表失败：" + e.getMessage());
        }
    }

    @PostMapping("/daily-task")
    public Result<String> createTask(@RequestBody DailyTask task) {
        try {
            dailyTaskService.createTask(task);
            return Result.success("创建任务成功");
        } catch (Exception e) {
            log.error("创建任务失败", e);
            return Result.error("创建任务失败：" + e.getMessage());
        }
    }

    @PutMapping("/daily-task/{id}")
    public Result<String> updateTask(@PathVariable Long id, @RequestBody DailyTask task) {
        try {
            task.setId(id);
            dailyTaskService.updateTask(task);
            return Result.success("更新任务成功");
        } catch (Exception e) {
            log.error("更新任务失败", e);
            return Result.error("更新任务失败：" + e.getMessage());
        }
    }

    @PutMapping("/daily-task/{id}/status")
    public Result<String> updateTaskStatus(
            @PathVariable Long id,
            @RequestBody Map<String, String> statusMap) {
        try {
            String status = statusMap.get("status");
            if (status == null) {
                return Result.error("状态不能为空");
            }
            dailyTaskService.updateTaskStatus(id, status);
            return Result.success("更新任务状态成功");
        } catch (Exception e) {
            log.error("更新任务状态失败", e);
            return Result.error("更新任务状态失败：" + e.getMessage());
        }
    }

    @DeleteMapping("/daily-task/{id}")
    public Result<String> deleteTask(@PathVariable Long id) {
        try {
            dailyTaskService.deleteTask(id);
            return Result.success("删除任务成功");
        } catch (Exception e) {
            log.error("删除任务失败", e);
            return Result.error("删除任务失败：" + e.getMessage());
        }
    }
}